package csc.daonjpa.java.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import csc.daonjpa.java.dao.CustomerDAO;
import csc.daonjpa.java.dao.CustomerDAOImpl;
import csc.daonjpa.java.dao.CustomerRoleDAO;
import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.domain.CustomerRole;

@Controller
@RequestMapping(value = "/register")
public class RegisterController {

	@Autowired
	private CustomerDAO customerDAO;

	@Autowired
	private CustomerRoleDAO customerRoleDAO;

	@ModelAttribute("customer")
	private Customer contructCustomer() {
		return new Customer();
	}

	@RequestMapping
	public String goRegister() {
		return "register";
	}

	@RequestMapping(value = "/registerform")
	public String resultRegister(@ModelAttribute("customer") Customer customer,
			Model model, BindingResult rs) {
		if (rs.hasErrors()) {
			model.addAttribute("message", "Sorry ! You register fail");
			return "register";
		}

		CustomerRole cr = new CustomerRole();
		if (customer.getLoginId().equals("admin")) {
			cr.setRole("ROLE_ADMIN");
		} else {
			cr.setRole("ROLE_USER");
		}
		
		String hashPassword = customer.getPassword();
		BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
		customer.setPassword(encode.encode(hashPassword));
		
		cr.setCustomer(customer);

		if (customerDAO.addCustomer(customer)
				&& customerRoleDAO.addCustomerRole(cr)) {

			model.addAttribute("message",
					"Congratulation ! You register successfully");
			return "index";

		} else {
			model.addAttribute("message", "Sorry ! You register fail");
			return "register";
		}
	}

}
